package com.newasia.shopping.services;

import com.alibaba.fastjson.JSON;
import com.newasia.shopping.IContentService;
import com.newasia.shopping.constant.GlobalConstants;
import com.newasia.shopping.constants.ShoppingRetCode;
import com.newasia.shopping.converter.ContentConverter;
import com.newasia.shopping.converter.ProductCateConverter;
import com.newasia.shopping.dal.entitys.*;
import com.newasia.shopping.dal.persistence.*;
import com.newasia.shopping.dto.*;
import com.newasia.shopping.dto.cateDto.ProductCateDto;
import com.newasia.shopping.services.cache.CacheManager;
import com.newasia.shopping.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 *主页菜单项
 * lyh
 */
@Slf4j
@Service
public class ContentServiceImpl implements IContentService {

//    @Autowired
//    PanelContentMapper panelContentMapper;
//
        @Autowired
        ContentConverter contentConverter;

        @Autowired
        PanelNavMapper panelNavMapper;

        @Autowired
        PanelNavUrlMapper panelNavUrlMapper;

        @Autowired
        ItemCatMapper itemCatMapper;

        @Autowired
        ProductCateConverter productCateConverter;

        @Autowired
        CacheManager cacheManager;

        @Autowired
        ItemSpuMapper itemSpuMapper;

        @Autowired
        ItemSkuMapper itemSkuMapper;

        @Autowired
        ItemSkuPermMapper itemSkuPermMapper;

    @Override
    public NavListResponse queryNavList(HomepageRequest homepageRequest) {
        NavListResponse response=new NavListResponse();
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        try {

            String json= cacheManager.checkCache(GlobalConstants.HOMEPAGE_NAV_CACHE_KEY+":"+homepageRequest.getMenuId());
            if(StringUtils.isNoneEmpty(json)){
                NavListResponse navListResponse = JSON.parseObject(json, NavListResponse.class);
                response.setData(navListResponse.getData());
                response.setProductCateDtoList(navListResponse.getProductCateDtoList());
                return response;
            }
//            PanelContentExample exampleContent = new PanelContentExample();
//            exampleContent.setOrderByClause("sort_order");
//            PanelContentExample.Criteria criteriaContent = exampleContent.createCriteria();
//            criteriaContent.andPanelIdEqualTo(GlobalConstants.HEADER_PANEL_ID);
//            List<PanelContent> pannelContents = panelContentMapper.selectByExample(exampleContent);
//            //添加缓存操作 TODO
//            response.setPannelContentDtos(contentConverter.panelContents2Dto(pannelContents));
            PanelNavExample panelNavExample = new PanelNavExample();
            panelNavExample.setOrderByClause("sort_order asc");
            List<PanelNav> panelNavs = panelNavMapper.selectByExample(panelNavExample);
            List<NavDto> navDtos = contentConverter.item2dto(panelNavs);
            List<Long> catList =new ArrayList<>();
            for (NavDto dto:navDtos) {
                if(dto.getType()==0&&dto.getCatId()!=null){
                    ItemCatExample eee=new ItemCatExample();
                    eee.createCriteria().andStatusEqualTo(1).andCatIdEqualTo(dto.getCatId());
                    List<ItemCat> itemCats = itemCatMapper.selectByExample(eee);
                    if(itemCats.size()>0){
                        ItemCat itemCat =itemCats.get(0);
                        dto.setNavName(itemCat.getCatName());
                        catList.add(itemCat.getCatId());
                    }
//
                }


                if(dto.getType()==1){
                    PanelNavUrlExample example=new PanelNavUrlExample();
                    example.createCriteria().andNavIdEqualTo(dto.getId());
                    example.setOrderByClause("sort_order asc");
                    List<PanelNavUrl> panelNavUrls = panelNavUrlMapper.selectByExample(example);
                    dto.setChildren(contentConverter.navitem2dto(panelNavUrls));
                }


                if(dto.getType()==2){
                    PanelNavUrlExample example=new PanelNavUrlExample();
                    example.createCriteria().andNavIdEqualTo(dto.getId());
                    example.setOrderByClause("sort_order asc");
                    List<PanelNavUrl> panelNavUrls = panelNavUrlMapper.selectByExample(example);
                    List<SpuNavItemDto> item=new ArrayList<>();

                    for (PanelNavUrl url:panelNavUrls) {
                        Long spuId = url.getItemId();

                        SpuNavItemDto nav =new SpuNavItemDto();
                        ItemSpu itemSpu = itemSpuMapper.selectByPrimaryKey(spuId);


                        ItemSkuExample eex=new ItemSkuExample();
                        eex.createCriteria().andStatusEqualTo(1);
                        List<ItemSku> itemSkus = itemSkuMapper.selectByExample(eex);
                        if(itemSkus.size()<=0){
                            continue;
                        }
                        ItemSku itemSku=itemSkus.get(0);
                        for (ItemSku s:itemSkus) {
                            if(itemSku.getSkuPrice().compareTo(s.getSkuPrice())==-1){
                                itemSku=s;
                            }
                        }


                        if(homepageRequest.getMenuId()!=null&&homepageRequest.getMenuId().longValue()!=0){
                            ItemSkuPermExample ee=new ItemSkuPermExample();
                            ee.createCriteria().andSkuIdEqualTo(itemSku.getSkuId()).andMenuIdEqualTo(homepageRequest.getMenuId());
                            List<ItemSkuPerm> itemSkuPerms = itemSkuPermMapper.selectByExample(ee);
                            if(itemSkuPerms.size()>0){
                                ItemSkuPerm itemSkuPerm = itemSkuPerms.get(0);
                                Integer type = itemSkuPerm.getType();
                                if(type.intValue()==0){
                                    BigDecimal percentage = itemSkuPerm.getPercentage();
                                    nav.setPrice(itemSku.getSkuPrice().multiply(percentage).setScale(0,BigDecimal.ROUND_DOWN));
                                }else{
                                    nav.setPrice(itemSkuPerm.getMoney());
                                }
                            }else {
                                nav.setPrice(itemSku.getSkuPrice());
                            }

                        }else{
                            nav.setPrice(itemSku.getSkuPrice());
                        }

                        nav.setCover(itemSpu.getImage());
                        nav.setTitle(itemSpu.getTitle());
                        nav.setSkuId(itemSku.getSkuId());
                        item.add(nav);

                    }


                    dto.setSpuNavDtos(item);

                }

            }
            List<ItemCat> list = new ArrayList<>();
            if(catList.size()>0){
            ItemCatExample itemCat = new ItemCatExample();

            itemCat.createCriteria().andCatIdIn(catList).andStatusEqualTo(1);
            itemCat.setOrderByClause("parent_id asc,sort_order asc");
            List<ItemCat> itemCats = itemCatMapper.selectByExample(itemCat);


            for (ItemCat i:itemCats) {
                if(i.getParentId()==null){
                    continue;
                }
                if(i.getParentId().longValue()==0){
                    list.add( listToTree(i,itemCats));
                }else{
                    break;
                }
            }
            }
            List<ProductCateDto> productCateDtos = productCateConverter.items2Dto(list);
            response.setProductCateDtoList(productCateDtos);




            response.setData(navDtos);
            cacheManager.setCache(GlobalConstants.HOMEPAGE_NAV_CACHE_KEY+":"+homepageRequest.getMenuId(),JSON.toJSONString(response),GlobalConstants.HOMEPAGE_EXPIRE_TIME);

        }catch (Exception e){
            log.error("ContentServiceImpl.queryNavList Occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            e.printStackTrace();
        }
        return response;
    }


    private ItemCat listToTree(ItemCat items, List<ItemCat> itemCats) {

        List<ItemCat> list = new ArrayList<>();

        for (ItemCat i: itemCats) {

            if(items.getCatId().longValue()==i.getParentId().longValue()){

                list.add(listToTree(i,itemCats));

            }

        }

        items.setChildren(list);
        return items;
    }


}
